package com.steven.im.areaselect;

import android.app.Dialog;
import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.steven.im.R;
import com.steven.im.entity.BaseEntity;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.ui.activity.AddaddrActivity;
import com.steven.im.utils.GsonUtils;
import com.steven.im.utils.SaveParameterUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import retrofit2.Response;

/**
 * @Author： 淘跑
 * @Date: 2018/5/29 15:40
 * @Use： 专为地址选择器打照的Dialog
 */
public class RxAreaSelectDialog extends Dialog {

    ImageView mIvClose;
    TabLayout mTlTitle;
    RecyclerView mRv;
    private OnSelectedResultCallBack resultCallBack;

    private AreaAdapter mAdapter;
    private Map<Integer, AreaBean> currentMap = new TreeMap<>();
    private View mContentView;

    private List<AreaBean> proList;
    String parentId = "100000";//城市父ID，默认一级
    int currentTab = 0;//当前省份序号

    public RxAreaSelectDialog(Context context) {
        super(context, R.style.RxDialog);
        init(context);
    }

    private Context mContext;

    private void init(Context context) {
        mContext = context;
        mContentView = LayoutInflater.from(context).inflate(R.layout.layout_bottom_sheet_dialog, null);
        mIvClose = mContentView.findViewById(R.id.iv_close);
        mTlTitle = mContentView.findViewById(R.id.tl_title);
        mRv = mContentView.findViewById(R.id.rv);
        setContentView(mContentView);
        initView();
        setAnimation(R.style.Dialog_ChooseAddress_Animation);
    }


    public void setAnimation(int id) {
        Window window = getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
//        params.height = DensityUtils.dp2px(context, 400);
        window.setAttributes(params);
        window.setWindowAnimations(id);
        window.setGravity(Gravity.BOTTOM);
    }

    private void initView() {
        proList = new ArrayList<>();
        mIvClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        mAdapter = new AreaAdapter(mContext);
        mAdapter.setOnSelectedListener(new AreaAdapter.OnSelectedListener() {
            @Override
            public void onSelected(Map<Integer, AreaBean> map, int pos) {
                if (pos >= 2) {
                    if (resultCallBack != null) {
                        String names = currentMap.get(pos).getMergerName();
                        String[] split = names.split(",");
                        if (split.length > 2) {
                            resultCallBack.onResult(currentMap.get(pos).getRegionId(),
                                    currentMap.get(pos).getMergerName().replace(",", ""),
                                    split[0], split[1], split[2]);
                        }
                    }
                    dismiss();
                } else {
                    currentMap = map;
                    mTlTitle.removeAllTabs();
                    for (Integer in : map.keySet()) {
                        mTlTitle.addTab(
                                mTlTitle.newTab().setText(map.get(in).getRegionName()));
                    }
                    addChooseTab();
                }
            }
        });
        final LinearLayoutManager manager = new LinearLayoutManager(getContext());
        mRv.setLayoutManager(manager);
        mRv.addItemDecoration(new LineAreaItemDecoration(getContext(), 2));
        mRv.setAdapter(mAdapter);

        mTlTitle.setTabMode(TabLayout.MODE_SCROLLABLE);
        mTlTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int pos = tab.getPosition();
                currentTab = pos;
                if (pos == 0) {//省份
                    getProList();
                } else {//其他
                    parentId = currentMap.get(pos - 1).getRegionId();
                    getCityList(pos, parentId);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        addChooseTab();
    }

    private void addChooseTab() {
        mTlTitle.addTab(mTlTitle.newTab().setText("请选择"), true);
//        TabLayoutUtil.reflex(mContext, mTlTitle);
    }

    public RxAreaSelectDialog(Context context, int themeResId) {
        super(context, themeResId);
        init(context);
    }

    public RxAreaSelectDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        init(context);
    }

    public void setResultCallBack(OnSelectedResultCallBack resultCallBack) {
        this.resultCallBack = resultCallBack;
    }

    public interface OnSelectedResultCallBack {

        void onResult(String regionId, String result, String province, String city, String area);
    }

    /**
     * 获取城市信息
     */
    private void getCityList(final int pos, final String parentId) {
        Task.getApiService().getRegion(parentId).enqueue(new MyCallback<BaseEntity>((AddaddrActivity) mContext) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    if ("0".equals(response.body().getCode())) {
                        List<AreaBean> areaList = GsonUtils.jsonToArrayList(
                                response.body().getResult().getJSONArray("regionList").toString(),
                                AreaBean.class);
                        if (areaList != null) {
                            if (currentTab == pos) {
                                proList.clear();
                                proList.addAll(areaList);
                                mAdapter.setData(pos, proList);
                                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRv.getLayoutManager();
                                mAdapter.moveToPosition(linearLayoutManager);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    /**
     * 获取省份信息
     */
    private void getProList() {
        Task.getApiService().addressInit().enqueue(new MyCallback<BaseEntity>((AddaddrActivity) mContext) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    SaveParameterUtils.saveToken(response.raw().header("token"));
                    if ("0".equals(response.body().getCode())) {
                        List<AreaBean> areaList = GsonUtils.jsonToArrayList(
                                response.body().getResult().getJSONArray("regionList").toString(),
                                AreaBean.class);
                        if (areaList != null) {
                            if (currentTab == 0) {
                                proList.clear();
                                proList.addAll(areaList);
                                mAdapter.setData(0, proList);
                                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRv.getLayoutManager();
                                mAdapter.moveToPosition(linearLayoutManager);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

}
